package phone.example.com.a36kr.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import phone.example.com.a36kr.R;
import phone.example.com.a36kr.other.CircleDrawable;
import phone.example.com.a36kr.other.mybmob.MyBmobUser;
import phone.example.com.a36kr.tools.BaseActivity;

/**
 * Created by dllo on 16/8/28.
 */
public class DetailedLoginActivity extends BaseActivity implements View.OnClickListener {

    private TextView revisePassword; // 更改密码
    private static String path = "/sdcard/myHead/";// sd路径
    private ImageView iconIv; //头像 id
    private Bitmap head;// 头像Bitmap
    private MyBmobUser bmobUser;
    @Override
    protected int setLayout() {
        return R.layout.activity_my_login_detailed;
    }

    @Override
    protected void initView() {
        // 头像
        iconIv = bindView(R.id.detailed_icon_iv);
        iconIv.setOnClickListener(this);


        /*************************退出登录 修改密码************************************/
        Button quitBtn = bindView(R.id.detailed_Login_quit);
        revisePassword = bindView(R.id.login_revise_password);
        revisePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alter = new AlertDialog.Builder(DetailedLoginActivity.this);
                alter.setTitle("更改密码");
                View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.register_password_dialog, null);
                final EditText oldPassEt = (EditText) view.findViewById(R.id.dialog_old_password);
                final EditText newPassEt = (EditText) view.findViewById(R.id.dialog_new_password);
                alter.setView(view);
                alter.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String oldPass = oldPassEt.getText().toString();
                        String newPass = newPassEt.getText().toString();
                        // 更改密码
                        BmobUser.updateCurrentUserPassword(oldPass, newPass, new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    Toast.makeText(DetailedLoginActivity.this, "密码修改成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(DetailedLoginActivity.this, "更改失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    }
                });
                alter.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(DetailedLoginActivity.this, "取消修改", Toast.LENGTH_SHORT).show();
                    }
                });
                alter.show();
            }
        });
        quitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iconIv.setImageDrawable(null);
                MyBmobUser.logOut();// 清除缓存用户对象
                MyBmobUser currentUser = (MyBmobUser) MyBmobUser.getCurrentUser();// 现在currentUser是null了
                Toast.makeText(DetailedLoginActivity.this, "currentUser:" + currentUser, Toast.LENGTH_SHORT).show();
                /**
                 * fragment发送广播
                 */
                Intent intent = new Intent();
                intent.setAction("com.36kr.android.out");
                Log.d("退出成功", "我发送了广播");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
                finish();

            }
        });
        /**************************帅气的分割符***************************************/
        MyBmobUser user = MyBmobUser.getCurrentUser(MyBmobUser.class);
        try {
            if (user.getUsername() != null){
                Bitmap bitmap = bmobUser.getIcon();
                if (bitmap != null) {
                    CircleDrawable circleDrawable = new CircleDrawable(bitmap);
                    iconIv.setImageDrawable(circleDrawable);

                }

            }
        }catch (Exception e){

        }


    }


    @Override
    protected void initData() {
        initPicture();
    }

    private void initPicture() {
        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");// 从SD卡中找头像，转换成Bitmap
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);// 转换成drawable
            iconIv.setImageDrawable(drawable);
        } else {
            /**
             * 如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */
            Toast.makeText(this, "SD卡没有图片正在从服务器获取", Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    public void onClick(View v) {
        // 更换头像
         showTypeDialog();

    }

    private void showTypeDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        final android.app.AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_select_photo, null);
        TextView tv_select_gallery = (TextView) view.findViewById(R.id.tv_select_gallery);
        TextView tv_select_camera = (TextView) view.findViewById(R.id.tv_select_camera);
        tv_select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                dialog.dismiss();
            }
        });
        tv_select_camera.setOnClickListener(new View.OnClickListener() {// 调用照相机
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
                startActivityForResult(intent2, 2);// 采用ForResult打开
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());// 裁剪图片
                }

                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));// 裁剪图片
                }

                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);// 保存在SD卡中
                        CircleDrawable circleDrawable = new CircleDrawable(head);
                        iconIv.setImageDrawable(circleDrawable);// 用ImageView显示出来
                        /*********更换头像*************/
                        bmobUser = MyBmobUser.getCurrentUser(MyBmobUser.class);
                        if (bmobUser != null){
                            bmobUser.setIcon(head);
                            bmobUser.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        Toast.makeText(getApplicationContext(), "正在更新", Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent();
                                        intent.setAction("com.36kr.android.updateHand");
                                        Log.d("头像更新成功", "我发送了广播");
                                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
                                    } else {
                                        Toast.makeText(getApplicationContext(), "更新失败", Toast.LENGTH_SHORT).show();
                                        Log.d("图片上传失败", "e:" + e);
                                    }
                                }
                            });
                        }else {
                            Toast.makeText(this, "请登录", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 调用系统的裁剪功能
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";// 图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
